'''
Created on Jul 5, 2009

@author: bryan
'''

#===============================================================================
# Imports
#===============================================================================
import gdata.spreadsheet.service
import getpass
import getopt
import sys
import string
import time

#===============================================================================
# Main Class
#===============================================================================
class Uploader(object):
    '''
    This class will allow the user to connect to a Google Spreadsheet and upload
    dictionary data.
    '''

    def __init__(self, email=None, password=None):
        "Initialize attributes of an Uploader."
        if not email:
            email = raw_input('Spreadsheets API | Text DB Tests\n'
                                 'Please enter your username(email): ')
        if not password:
            password = getpass.getpass()
        self.gd_client = gdata.spreadsheet.service.SpreadsheetsService()
        self.gd_client.email = email
        self.gd_client.password = password
        self.gd_client.ProgrammaticLogin()
        self.curr_key = ''
        self.curr_wksht_id = ''
        self.list_feed = None
        
    def _PromptForSpreadsheet(self,book=None):
        # Get the list of spreadsheets
        feed = self.gd_client.GetSpreadsheetsFeed()
        self._PrintFeed(feed)
        if book == None:
            input = raw_input('\nSelection: ')
        else:
            input = book
        id_parts = feed.entry[string.atoi(input)].id.text.split('/')
        self.curr_key = id_parts[len(id_parts) - 1]
      
    def _PromptForWorksheet(self,sheet=None):
        # Get the list of worksheets
        feed = self.gd_client.GetWorksheetsFeed(self.curr_key)
        self._PrintFeed(feed)
        if sheet == None:
            input = raw_input('\nSelection: ')
        else:
            input = sheet
        id_parts = feed.entry[string.atoi(input)].id.text.split('/')
        self.curr_wksht_id = id_parts[len(id_parts) - 1]
    
    def _GetWorksheet(self,sheet_name):
        feed = self.gd_client.GetWorksheetsFeed(self.curr_key)
        for i,entry in enumerate(feed.entry):
            if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed):
                if sheet_name == entry.title.text:
                    id_parts = entry.id.text.split('/')
                    self.curr_wksht_id = id_parts[len(id_parts) - 1]
      
    def _PrintFeed(self, feed):
        for i, entry in enumerate(feed.entry):
            if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed):
                print '%s %s\n' % (entry.title.text, entry.content.text)
            elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed):
                print '%s %s %s\n' % (i, entry.title.text, entry.content.text)
            else:
                print '%s %s\n' % (i, entry.title.text)
    
    def set_spreadsheet(self, spreadsheet):
        "Set the spreadsheet we're using by its ID."
        self.curr_key = spreadsheet
      
    def set_worksheet(self, worksheet):
        "Set the worksheet (a page of a spreadsheet) we're using by its ID."
        self.curr_wksht_id = worksheet
    
    def _list_insert_action(self, row_data):
        "Insert a new row with data."
        entry = self.gd_client.InsertRow(row_data,
            self.curr_key, self.curr_wksht_id)
        if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
            print 'Inserted!'
            
    def Write(self,dict_to_write):
        """
        dict_to_write is a dictionary that will be written to the table opened
        by Setup.
        """
        try:
            print "key: ", self.curr_key, "id: ", self.curr_wksht_id
            entry = self.gd_client.InsertRow(dict_to_write,
                                             self.curr_key, self.curr_wksht_id)
            entry
            if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
                print "Success! Data written to Google Spreadsheet."
        except:
            print "Error writing to Google Spreadsheet"
            print gdata.service.RequestError()
            
    def _run(self,sheet=None,book=None):
        "Fill in a blank worksheet."
        self._PromptForSpreadsheet(book)
        self._PromptForWorksheet(sheet)
            
def main():
    usage = 'python UploadToGoogle.py --user [username] --pw [password]'
    # parse command line options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw="])
    except getopt.error, msg:
        print usage
        sys.exit(2)
  
    user = ''
    pw = ''
    key = ''
    # Process options
    for o, a in opts:
        if o == "--user":
            user = a
        elif o == "--pw":
            pw = a

    if user == '' or pw == '' or len(args) < 1:
        print usage
        sys.exit(2)
        
    uploader = Uploader(user, pw)
    uploader._run()

if __name__ == '__main__':
    main()
           
            